<?php
namespace app\admin\controller;
use app\__MODULE__\model\{Goods as GoodsModel,StoreCategory,GoodsAttr,ProductRule,GoodsAttrResult,GoodsAttrValue};
use think\facade\Db;
use app\common\BaseController;

class Goods extends BaseController {

	/**
	 * [index 首页列表]
	 * @return [type] [description]
	 */
	public  function index(){
        $page  = (int)request()->param('page/d', 0);
        $limit  = (int)request()->param('limit/d', 10);
        $search = request()->param();
        $where = [];
        $where[] = ['is_del','=',0];
        if(isset($search["title"]) && $search["title"]!="") $where[] = ["title","=",$search["title"]];
        if(isset($search["cate_id"]) && $search["cate_id"]!="") $where[] = ["cate_id","=",$search["cate_id"]];
        $query  = GoodsModel::with(['cate'])->where($where);
        $total  = $query->count();
        $data   = $query->page($page,$limit)->order('id desc')->select();
        $category  = StoreCategory::getTierList();;
        $rule_list  = ProductRule::field('id,rule_name,rule_value')->select();
        foreach ($rule_list as $key => $value) {
            $value["rule_value"] = json_decode($value["rule_value"],true);
        }
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
            'category' => $category,
            'rule_list' => $rule_list
        ]);
	}




    /**
     * 编辑
     * @return [type] [description]
     */
    public function edit(){
        $id  = param_check('id');
        if(request()->isPost()) {
            $data = request()->post();
            $detail = $data['attrs'];
            $data['price'] = min(array_column($detail, 'price'));
            $data['ot_price'] = min(array_column($detail, 'ot_price'));
            $data['cost'] = min(array_column($detail, 'cost'));
            $attr = $data['items'];
            unset($data['items'], $data['video'], $data['attrs']);
            if (count($data['cate_id']) < 1) json_response(0,'请选择产品分类');
            if (!$data['store_name']) json_response(0,'请输入产品名称');
            if (!$data['image']) json_response(0,'请上传产品图片');
            if (count($data['slider_image']) < 1) json_response(0,'请上传产品轮播图');
            $data['stock']        = array_sum(array_column($detail, 'stock'));
            unset($data['sales']);
            try{
                GoodsModel::update($data,['id'=>$id]);
            if ($data['spec_type'] == 0) {
                $attr = [
                    [
                        'value' => '规格',
                        'detailValue' => '',
                        'attrHidden' => '',
                        'detail' => ['默认']
                    ]
                ];
                $detail[0]['value1'] = '规格';
                $detail[0]['detail'] = ['规格' => '默认'];
            }

            $attr_res = GoodsAttr::createProductAttr($attr, $detail, $id);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());
            }
            json_response(1,'编辑成功');
        }
    }

       /**
     * 获取产品详细信息
     * @param int $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_product_info()
    {
        $id   = request()->param('id');
        $data['productInfo'] = [];
        if ($id) {
            $productInfo = GoodsModel::where('id',$id)->field('id,image,slider_image,store_name,store_info,keyword,bar_code,cate_id,price,ot_price,cost,unit_name,stock,is_show,is_hot,is_new,video_link,spec_type,description,sort')->find();
            if (!$productInfo) {
                json_response(0,'修改的产品不存在');
            }
            $productInfo['description'] = htmlspecialchars_decode($productInfo['description']);
            if ($productInfo['spec_type'] == 1) {
                $result = GoodsAttrResult::getResult($id);
                foreach ($result['value'] as $k => $v) {
                    $num = 1;
                    foreach ($v['detail'] as $dv) {
                        $result['value'][$k]['value' . $num] = $dv;
                        $num++;
                    }
                }
                $productInfo['items'] = $result['attr'];
                $productInfo['attrs'] = $result['value'];
                $productInfo['attr'] = ['pic' => '', 'price' => 0, 'cost' => 0, 'ot_price' => 0, 'stock' => 0, 'bar_code' => ''];
            } else {
                $result = GoodsAttrValue::where('product_id', $id)->find();
                if ($result) {
                    $single = $result->toArray();
                } else {
                    $single = [];
                }
                $productInfo['items'] = [];
                $productInfo['attrs'] = [];
                $productInfo['attr'] = [
                    'pic' => $single['image'] ?? '',
                    'price' => $single['price'] ?? 0,
                    'cost' => $single['cost'] ?? 0,
                    'ot_price' => $single['ot_price'] ?? 0,
                    'stock' => $single['stock'] ?? 0,
                    'bar_code' => $single['bar_code'] ?? ''
                ];
            }
        }
        json_response(1,'success',$productInfo);
    }
    

    /**
     * 添加商品
     */
    public function create(){
        if(request()->isPost()) {
            $data = request()->post();
            $detail = $data['attrs']; //商品列表，数组格式。单属性一条，多属性多条
            $data['price']    = min(array_column($detail, 'price')); // 取最小价格
            $data['ot_price'] = min(array_column($detail, 'ot_price')); // 取最小原价
            $data['cost']     = min(array_column($detail, 'cost'));  //取最小成本价
            $attr = $data['items'];  //提交的商品规格总览,数组格式  多属性商品专有
            unset($data['items'], $data['video'], $data['attrs']);
            if (count($data['cate_id']) < 1)      json_response(0,'请选择产品分类');
            if (!$data['store_name'])             json_response(0,'请输入产品名称');
            if (!$data['image'])                  json_response(0,'请上传产品图片');
            if (count($data['slider_image']) < 1) json_response(0,'请上传产品轮播图');
            $data['stock']        = array_sum(array_column($detail, 'stock')); //库存相加为总库存
            Db::startTrans();
            try{
                $goods_insert = GoodsModel::create($data);
                if ($data['spec_type'] == 0) { 
                    //单属性 规则写出是默认
                    $attr = [
                        [
                            'value' => '规格',
                            'detailValue' => '',
                            'attrHidden' => '',
                            'detail' => ['默认']
                        ]
                    ];
                    $detail[0]['value1'] = '规格';
                    $detail[0]['detail'] = ['规格' => '默认'];
                }
                //写入属性表
                $attr_res = GoodsAttr::createProductAttr($attr, $detail, $goods_insert->id);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                json_response(0,$e->getMessage());
            }
            json_response(1,'添加成功');
        }
        
    }

        /**
     * 获取规则属性模板
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_rule()
    {
        return json_response(1,'success',ProductRule::field(['rule_name', 'rule_value'])->select()->each(function ($item) {
            $item['rule_value'] = json_decode($item['rule_value'], true);
        })->toArray());
    }

    /**
     * 生成属性
     * @param int $id
     */
    public function is_format_attr()
    {

        $data = request()->post();
        $data['attrs'] = request()->param('attrs/a',[]);
        $data['items'] = request()->param('items/a',[]);
        $id  = request()->param('id/d',0);
        $type  = request()->param('type/d',0);
        $attr = $data['attrs'];
        $value = attr_format($attr)[1];
        $valueNew = [];
        $count = 0;
        foreach ($value as $key => $item) {
            $detail = $item['detail'];
            sort($item['detail'], SORT_STRING);
            $suk = implode(',', $item['detail']);
            $types = 1;
            if ($id) {
                $sukValue = GoodsAttrValue::where('product_id', $id)->where('suk', $suk)->column('bar_code,cost,price,ot_price,stock,image as pic', 'suk');
                if (!count($sukValue)) {
                    if ($type == 0) $types = 0; //编辑商品时，将没有规格的数据不生成默认值
                    $sukValue[$suk]['pic'] = '';
                    $sukValue[$suk]['price'] = 0;
                    $sukValue[$suk]['cost'] = 0;
                    $sukValue[$suk]['ot_price'] = 0;
                    $sukValue[$suk]['stock'] = 0;
                    $sukValue[$suk]['bar_code'] = '';
                }
            } else {
                $sukValue[$suk]['pic'] = '';
                $sukValue[$suk]['price'] = 0;
                $sukValue[$suk]['cost'] = 0;
                $sukValue[$suk]['ot_price'] = 0;
                $sukValue[$suk]['stock'] = 0;
                $sukValue[$suk]['bar_code'] = '';
            }
            if ($types) { //编辑商品时，将没有规格的数据不生成默认值
                foreach (array_keys($detail) as $k => $title) {
                    $header[$k]['title'] = $title;
                    $header[$k]['align'] = 'center';
                    $header[$k]['minWidth'] = 130;
                }
                foreach (array_values($detail) as $k => $v) {
                    $valueNew[$count]['value' . ($k + 1)] = $v;
                    $header[$k]['key'] = 'value' . ($k + 1);
                }
                $valueNew[$count]['detail'] = $detail;
                $valueNew[$count]['pic'] = $sukValue[$suk]['pic'] ?? '';
                $valueNew[$count]['price'] = $sukValue[$suk]['price'] ? floatval($sukValue[$suk]['price']) : 0;
                $valueNew[$count]['cost'] = $sukValue[$suk]['cost'] ? floatval($sukValue[$suk]['cost']) : 0;
                $valueNew[$count]['ot_price'] = isset($sukValue[$suk]['ot_price']) ? floatval($sukValue[$suk]['ot_price']) : 0;
                $valueNew[$count]['stock'] = $sukValue[$suk]['stock'] ? intval($sukValue[$suk]['stock']) : 0;
                $valueNew[$count]['bar_code'] = $sukValue[$suk]['bar_code'] ?? '';
                $count++;
            }
        }
        $header[] = ['title' => '图片', 'slot' => 'pic', 'align' => 'center', 'minWidth' => 80];
        $header[] = ['title' => '售价', 'slot' => 'price', 'align' => 'center', 'minWidth' => 120];
        $header[] = ['title' => '成本价', 'slot' => 'cost', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '原价', 'slot' => 'ot_price', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '库存', 'slot' => 'stock', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '产品编号', 'slot' => 'bar_code', 'align' => 'center', 'minWidth' => 140];
        $header[] = ['title' => '操作', 'slot' => 'action', 'align' => 'center', 'minWidth' => 70];
        $info = ['attr' => $attr, 'value' => $valueNew, 'header' => $header];
        return json_response(1,'success',$info);
    }

    /**
     * 商品删除
     * @return [type] [description]
     */
    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function del()
    {
        $id = request()->post('ids');
        if (!$id) return $this->failed('数据不存在');
        if (!GoodsModel::where('id','in',$id)->count()) json_response(0,'产品数据不存在');
        if (!GoodsModel::update(['is_del'=>1], ['id'=>['in',$id]])){
              return json_response(0,'删除失败,请稍候再试!');
          }else{
            return json_response(1,'删除成功!');
          }
    }

}
